/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.nutmotion.service;

import com.nutmotion.application.EMF;
import com.nutmotion.model.jpa.Trade;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.http.HttpServlet;

/**
 *
 * @author Manu
 */
public class TradeService {
    private EntityManager em;
    
    public TradeService() {
        this.em = EMF.createEntityManager();
    }
    
    /**
     * Finds matching trade(s) in the database
     * @param tradeToMatch
     * @return 
     */
    public List<Trade> match(Trade tradeToMatch) {
        SelectClauseStringBuilder selectClauseStringBuilder = new SelectClauseStringBuilder();
        FromClauseStringBuilder fromClauseStringBuilder = new FromClauseStringBuilder();
        WhereClauseStringBuilder whereClauseStringBuilder = new WhereClauseStringBuilder();                
        
        //First we build the SELECT clause
        selectClauseStringBuilder.append("t");
        
        //then the FROM clause
        fromClauseStringBuilder.append("Trade t")
                                .append("JOIN t.stock s")
                                .append("JOIN t.user u");
        
        
        //then the WHERE clause
        
        //match trade        
        whereClauseStringBuilder.append("t.name", tradeToMatch.getName())
        
        //match stock
                                .append("s.id", tradeToMatch.getStock().getId())     
                                .append("s.name", tradeToMatch.getStock().getName())
                                .append("s.ticker", tradeToMatch.getStock().getTicker())     
        
        //match user
                                .append("u.id", tradeToMatch.getUser().getId())
                                .append("u.nickname", tradeToMatch.getUser().getNickname());        
        
        System.out.println(selectClauseStringBuilder+" "+fromClauseStringBuilder+" "+whereClauseStringBuilder);
        return (List<Trade>) em.createQuery(selectClauseStringBuilder+" "+fromClauseStringBuilder+" "+whereClauseStringBuilder
                +" ORDER BY t.id").getResultList();        
    }        
    
    public void create(Trade trade) {
        em.getTransaction().begin();
        em.merge(trade);
        em.persist(trade);
        em.getTransaction().commit();
    }
}
